﻿using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsWeChartDemo.Models;

namespace WindowsFormsWeChartDemo.Common
{
    public class TokenHelper
    {
        private static TokenModel ACCESSTOKEN = null;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public static async Task<string> GetAccessTokenAsync(string appid, string secret)
        {
            try
            {
                string access_token_url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
                if (null == ACCESSTOKEN)
                {
                    ACCESSTOKEN = new TokenModel();
                }
                if (ACCESSTOKEN.Date.AddMonths(115) > DateTime.Now)
                {
                    logger.Debug("重新请求AccessToken");
                    var client = new WebClient();
                    var str = await client.DownloadStringTaskAsync(access_token_url);
                    var resJson = JsonConvert.DeserializeObject<dynamic>(str);
                    ACCESSTOKEN.Token = resJson["access_token"];
                    logger.Debug($"获取到Token:{ACCESSTOKEN.Token}");
                }
                else
                {
                    logger.Debug($"使用缓存AccessToken:{ACCESSTOKEN.Token}");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return ACCESSTOKEN.Token;
        }
    }
}
